using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace Space_Conquest
{
    /// <summary>
    /// Connects to one or more Clients, and sends messages back and forth
    /// </summary>
    public class Server : SocketConnection
    {

        #region Private Members

        List<Socket> clientConnections = new List<Socket>();

        #endregion

        #region Properties

        #endregion
         
        #region Constructors

        public Server() :
            this(2344)
        {
        }

        public Server(int portNumber) :
            base()
        {

            m_port = portNumber;

            OnConnectionError += new ConnectionErrorEventHandler(SimpleServer_OnConnectionError);

            IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, portNumber);
            m_mainSocket.Bind(ipLocal);
            m_mainSocket.Listen(3);
            m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);

        }

        #endregion

        #region Methods

        void SimpleServer_OnConnectionError(Socket source)
        {

            // Remove the disconnected client from the list of clients
            clientConnections.Remove(source);

        }

        public override void SendData(object obj)
        {

            foreach (Socket client in clientConnections)
            {

                client.Send(FullSerialize(obj));

            }
        }

        public virtual void SendData(object obj, int clientIndex)
        {

            if (clientIndex >= 0 && clientIndex < clientConnections.Count)
            {

                clientConnections[clientIndex].Send(FullSerialize(obj));

            }

        }

        protected void OnClientConnect(IAsyncResult asyn)
        {

            Socket newClient = m_mainSocket.EndAccept(asyn);
            clientConnections.Add(newClient);
            WaitForMeta(newClient);
            m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);

        }

        #endregion

    }
}
